import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  PixelRatio,
  NativeModules,
  InteractionManager,
  DeviceEventEmitter,
  Image,
  SafeAreaView,
  BackHandler
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
// import obj from '@/common/utils/obj';
import { calculatJD } from '@/common/util';
import order from '@/api/order';
import DashLine from '@/common/dashLine';
import { msg, BackImageOn, XMHeader } from '@/common';
import HeadTabs from '@/components/HeadTabs';
import {
  isAndroid,
  px2dp,
  fontColorBlack,
  fontColorCoffee,
  screenHeight
} from '@/styles';
import oil from '@/api/oil';
import {
  iconActivationFlag,
  iconDown,
} from '@/images';
import TransactionsRecordModal from '../components/transactions-record-modal';
import XmList from '../../../components/XmList';

// let { height } = obj;
let topHeight = null;

/**
 * @author kanglang
 * @description 油卡订单
 * @createDate 2020/8/14
 *
 */
export default class OilOrder extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSourse: [],
      toOrder: -1,
      status: 0,
      pageNo: 1,
      pageSize: 4,
      isLoading: true,
      showFoot: 1, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
      modalIsShow: false,
      optionIndex: 0,
      viewTitle: '国炬油卡订单'
    };
  }

  componentDidMount() {
    NativeModules.WindowModule.dismissLoading();
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { toOrder, cardType } = params;
    navigation.setParams({
      _handleBack: this._handleBack
    });
    if (cardType !== undefined) {
      this.setState({
        optionIndex: cardType,
        // viewTitle: cardType ? '实体油卡订单' : '国炬油卡订单',
        // status: cardType ? -1 : 0
      });
    }
    this.updateOrders = DeviceEventEmitter.addListener('updateOrder', e => {
      if (e) {
        this.setState({
          pageNo: 1
        }, () => {
          InteractionManager.runAfterInteractions(() => {
            this.loadData();
          });
        });
      } else {
        console.log('失败了呀');
      }
    });
    InteractionManager.runAfterInteractions(() => {
      this.loadData();
    });
    if (isAndroid) {
      BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
    }
  }

  componentWillUnmount() {
    if (isAndroid) {
      BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
    }
    this.updateOrders.remove();
  }

  optionSource = [
    // { id: 1, text: '实体油卡订单' },
    { id: 0, text: '国炬油卡订单' },
  ]

  tabSources = {
    1: [
      { tab: '全部', type: -1 },
      { tab: '待支付', type: 0 },
      { tab: '已完成', type: 4 }
    ],
    0: [
      { tab: '全部', type: 0 },
      { tab: '待拨油', type: 1 },
      { tab: '已拨油', type: 2 }
    ]
  };

  renderHead = () => {
    const { modalIsShow, viewTitle } = this.state;
    const { navigation } = this.props;
    return (
      <XMHeader
        renderTitle={() => {
          return (
            <View style={styles.headTitleContainer}>
              <Text style={styles.headTitleText}>{viewTitle}</Text>
            </View>
          );
        }}
        renderLeft={() => {
          return (
            <BackImageOn onClick={() => {
              const { _handleBack } = navigation.state.params;
              !!_handleBack && _handleBack();
            }}
            />
          );
        }}
      />
    );
  }

  render() {
    const { status, showFoot, isLoading, dataSourse, modalIsShow, optionIndex } = this.state;
    return (
      <SafeAreaView style={styles.container}>
        <View style={{ backgroundColor: '#F5F4F2', flex: 1 }}>
          {this.renderHead()}
          <HeadTabs
            tabSources={this.tabSources[optionIndex]}
            changeStatus={(type) => this._changeStatus(type)}
            status={status}
          />
          <XmList
            sources={dataSourse}
            renderItem={data => (optionIndex ? this._renderRow(data) : this._renderItem(data))}
            isLoading={isLoading}
            onDropdownRefresh={() => this.loadData()}
            onPullUpMore={() => this.LoadMore()}
            singleKey={item => item.id}
            showFoot={showFoot}
          />
          {/* {modalIsShow && (
            <TransactionsRecordModal
              activationFlag={iconActivationFlag}
              optionSource={this.optionSource}
              optionIndex={optionIndex}
              optionClick={({ id, text }) => {
                this.setState({
                  optionIndex: id,
                  viewTitle: text,
                }, () => {
                  this._changeStatus(this.tabSources[id][0].type);
                  this.setState({ modalIsShow: false });
                });
              }}
              modalClick={() => this.setState({ modalIsShow: false })}
            />
          )} */}
        </View>
      </SafeAreaView>
    );
  }

  // 下拉刷新
  loadData() {
    this.setState({
      isLoading: true,
      pageNo: 1,
      dataSourse: []
    }, () => {
      this.listInit(this.state.pageNo, this.state.pageSize, this.state.status, 'dropdown');
    });
  }

  // 上拉加载更多
  LoadMore() {
    this.setState({ showFoot: 2 });
    this.listInit(this.state.pageNo, this.state.pageSize, this.state.status, 'pullMore');
  }

  listInit(pageNo, pageSize, status, type) {
    const { optionIndex } = this.state;
    let apiName = optionIndex ? order.orderPage : oil.getPumpDetail;
    InteractionManager.runAfterInteractions(() => {
      apiName({
        status,
        pageSize,
        pageNo
      }).then(res => {
        let { dataSourse } = this.state;
        console.log('=====>>>', res.data);
        const newList = optionIndex ? res.data.result : res.data.records;
        if (res.success) {
          if (res.data.total === 0) {
            this.setState({
              isLoading: false,
              showFoot: 0
            });
            return;
          }
          if (newList.length <= 0) {
            this.setState({
              isLoading: false,
              showFoot: 1
            });
            return;
          }
          if (type === 'dropdown') {
            dataSourse = newList.concat(dataSourse);
          } else if (type === 'pullMore') {
            dataSourse = dataSourse.concat(newList);
          }
          this.setState({
            pageNo: this.state.pageNo + 1,
            dataSourse
          });
          if (newList.length <= this.state.pageSize) {
            this.setState({
              isLoading: false,
              showFoot: 1
            });
          }
        } else {
          this.setState({
            isLoading: false,
            showFoot: 0
          });
          msg.emit('app:tip', { text: res.msg });
        }
      }).catch(err => {
        this.setState({
          isLoading: false,
          showFoot: 0
        });
      });
    });
  }

  // 实体油卡元素
  _renderRow(data) {
    const jsAmount = calculatJD(data.item.amount);
    const currTime = data.item.orderTime;
    const partTime = currTime && currTime.substring(5, 16);
    const payChannel = data && data.item && data.item.payChannel;
    const jsIntegral = calculatJD(data.item.integral);
    return (
      <TouchableOpacity
        activeOpacity={1}
        onPress={this._orderDetail.bind(this, data.item)}
      >
        <View style={data.index === 0 ? [styles.item, styles.mt12] : styles.item}>
          <View style={styles.itemFlexB}>
            <View>
              <Text style={[styles.f16, styles.bBlack, styles.mb4]}>{data.item.productName}</Text>
              <Text style={[styles.bGlack]}>
                卡号：
                {data.item.oilAccountNo}
              </Text>
            </View>
            {
              data.item.status === 0 ? <Text style={styles.active}>待支付</Text> : (
                data.item.status === 4 ? (
                  <Text style={styles.success}>已支付</Text>
                ) : data.item.status === 5 ? <Text style={styles.gray}>已取消</Text> : <Text />
              )
            }
          </View>
          {
            data.item.status === 0 ? (
              <View style={{ marginTop: 30 }}>
                <View style={styles.itemFlexC}>
                  {/* <View> */}
                  {/*  <Text style={styles.timeColor}>{partTime}</Text> */}
                  {/* </View> */}
                  {
                    Number(jsIntegral) > 0 && (
                      <Text style={styles.integral}>
                        金豆抵扣:
                        <Text style={styles.integralPrice}>
                          ¥
                          {jsIntegral}
                        </Text>
                      </Text>
                    )
                  }
                  <Text style={{ color: '#666564' }}>
                    {data.item.status === 4 ? '实付金额' : '应付金额'}
                    {' '}
                    ¥
                    {jsAmount}
                  </Text>
                </View>
                <DashLine style={{ marginTop: 12 }} />
                <View style={{ flexDirection: 'row', marginTop: 16, justifyContent: 'flex-end' }}>
                  <TouchableOpacity
                    activeOpacity={1}
                    style={[
                      styles.btnStyle,
                      styles.borderC,
                      payChannel !== 6 && payChannel !== 11 && { marginRight: 16 }
                    ]}
                    onPress={this.cancels.bind(this, data.item)}
                  >
                    <Text style={styles.loginText}>取消</Text>
                  </TouchableOpacity>
                  {
                    payChannel !== 6 && payChannel !== 11
                      ? (
                        <LinearGradient
                          start={{ x: 0.0, y: 0 }}
                          end={{ x: 1, y: 0 }}
                          colors={['rgba(186,145,74,1)', 'rgba(186,145,74,1)']}
                          style={[styles.btnStyle]}
                        >
                          <TouchableOpacity
                            onPress={this._toPay.bind(this, data.item)}
                          >
                            <Text style={styles.white}>去支付</Text>
                          </TouchableOpacity>
                        </LinearGradient>
                      ) : null
                  }
                </View>
              </View>
            ) : (
              <View style={{ marginTop: 60 }}>
                <View style={styles.itemFlexB}>
                  <View>
                    <Text style={styles.timeColor}>{partTime}</Text>
                  </View>
                  <Text style={{ color: '#666564' }}>
                    {data.item.status === 4 ? '实付金额' : '应付金额'}
                    {' '}
                    ¥
                    {jsAmount}
                  </Text>
                </View>
              </View>
            )
          }
        </View>
      </TouchableOpacity>
    );
  }

  // 电子油卡
  _renderItem = (data) => {
    let statusTextStyle = {
      0: styles.active,
      1: styles.success,
    };
    return (
      <TouchableOpacity
        activeOpacity={1}
        onPress={() => {
          msg.emit('router: goToNext', {
            routeName: 'FictitiousOilCardOrderDetail',
            cardData: data.item
          });
        }}
      >
        <View
          style={
            data.index === 0 ? [styles.item, styles.mt12] : styles.item
          }
        >
          <View style={styles.itemFlexB}>
            <View>
              <Text style={[styles.f16, styles.bBlack, styles.mb4]}>{data.item.legalName}</Text>
              <Text style={[styles.bGlack]}>{`商户：${data.item.allianceName}`}</Text>
              {data.item.carNo && <Text style={[styles.bGlack, { marginTop: px2dp(5) }]}>{`车牌号：${data.item.carNo}`}</Text>}
            </View>
            <Text
              style={
                statusTextStyle[data.item.status.value] || styles.gray
              }
            >
              {data.item.status.name}
            </Text>
          </View>
          <View style={{ marginTop: 60 }}>
            <View style={styles.itemFlexB}>
              <View />
              <Text style={{ color: '#666564' }}>{`拨油金额：¥${data.item.oilPumpAmount}`}</Text>
            </View>
          </View>
        </View>
      </TouchableOpacity>
    );
  }

  callBacks(e, item) {
    if (e === 1) {
      order.closeOrderApp({ orderNo: item.orderNo }).then(res => {
        if (res.success) {
          this.setState({ status: -1, pageNo: 1, dataSourse: [] }, () => {
            this.loadData();
          });
        } else {
          msg.emit('app:messageBox', {
            isVisible: true,
            title: '提示',
            text: res.msg,
            okText: '确定',
            isClickBg: false,
          });
        }
      }).catch(res => {
        msg.emit('app:messageBox', {
          isVisible: true,
          title: '提示',
          text: res.msg,
          okText: '确定',
          isClickBg: false,
        });
      });
    }
  }

  cancels(item) {
    // NativeModules.WindowModule.showWindow({content: "确认要取消订单吗?", title: '提示'}, (es) => {
    //   this.callBacks(es, item)
    // })
    msg.emit('app:messageBox', {
      isVisible: true,
      title: '提示',
      text: '确认要取消订单吗?',
      okText: '确定',
      cancelText: '取消',
      okFn: () => {
        this.callBacks(1, item);
      },
      cancelFn: () => {
      },
    });
  }

  onLayout = (event) => {
    topHeight = event.nativeEvent.layout.height;
  }

  _orderDetail(data, e) {
    msg.emit('router: goToNext', {
      orderNo: data.orderNo,
      toDetail: 0,
      routeName: 'OilOrderDetail',
      allianceMemId: data.allianceMemId
    });
  }

  _toPay(data, e) {
    e.stopPropagation();
    data.amountNeed = calculatJD(Number(data.amount) + Number(data.integral));
    msg.emit('router: goToNext', {
      routeName: 'PayOrder',
      data: Object.assign(data, { goodsName: data.productName }),
      routerFrom: 'oilCard',
      allianceMemId: data.allianceMemId
    });
  }

  onBackAndroid = () => {
    this._handleBack();
    return true;
  }

  _handleBack() {
    msg.emit('router: refreshRoute', {
      routeName: 'Tab',
    });
    DeviceEventEmitter.emit('UPDATE_INTEGRAL', true);
    msg.emit('router: back');
  }

  _changeStatus(type) {
    this.setState({ status: type, pageNo: 1, dataSourse: [] }, () => {
      InteractionManager.runAfterInteractions(() => {
        this.loadData();
      });
    });
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  bank: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center',
    borderRadius: px2dp(10) * 2,
    backgroundColor: 'white',
    height: px2dp(90) * 2,
    padding: px2dp(16) * 2,
  },
  btnStyle: {
    width: px2dp(80) * 2,
    height: px2dp(30) * 2,
    borderRadius: px2dp(4) * 2,
    borderWidth: px2dp(1) * 2,
    borderColor: 'transparent',
    alignItems: 'center',
    justifyContent: 'center'
  },
  borderC: {
    borderColor: '#CCCAC8',
  },
  white: {
    color: '#fff'
  },
  center: {
    alignItems: 'center'
  },
  bBlack: {
    color: '#333232'
  },
  bGray: {
    color: '#666564'
  },
  gray: {
    color: '#999796'
  },
  active: {
    color: 'rgba(186,145,74,1)'
  },
  success: {
    color: '#1ABD13'
  },
  Image: {
    width: px2dp(54) * 2,
    height: px2dp(44) * 2,
    marginRight: px2dp(8) * 2
  },
  mb4: {
    marginBottom: px2dp(4) * 2
  },
  f18: {
    fontSize: px2dp(18) * 2,
  },
  f16: {
    fontSize: px2dp(16) * 2,
  },
  f20: {
    fontSize: px2dp(20) * 2,
  },
  f28: {
    fontSize: px2dp(28) * 2,
  },
  flexB: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center',
  },
  bWhite: {
    backgroundColor: '#fff'
  },
  choose: {
    padding: px2dp(6) * 2,
    borderBottomWidth: 3 / PixelRatio.get(),
    borderColor: '#FFF'
  },
  active: {
    borderColor: 'rgba(186,145,74,1)',
    color: 'rgba(186,145,74,1)'
  },
  list: {
    height: screenHeight - topHeight,
  },
  itemFlexB: {
    flexDirection: 'row',
    justifyContent: 'space-between'
  },
  itemFlexC: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
  },
  item: {
    borderRadius: px2dp(12) * 2,
    backgroundColor: '#FFF',
    marginTop: px2dp(12) * 2,
    marginLeft: px2dp(12) * 2,
    marginRight: px2dp(12) * 2,
    padding: px2dp(12) * 2
  },
  mt12: {
    marginTop: px2dp(12) * 2
  },
  modalViewStyle: {
    width: '100%',
    height: '100%',
    backgroundColor: 'rgba(0, 0, 0, 0.3)',
    justifyContent: 'center',
    alignItems: 'center',
    position: 'absolute',
  },
  footer: {
    justifyContent: 'center',
    alignItems: 'center'
  },
  backImg: {
    width: px2dp(18) * 2,
    height: px2dp(18) * 2,
    marginLeft: px2dp(12) * 2,
  },
  bGlack: {
    color: '#666564'
  },
  timeColor: {
    color: '#999796'
  },
  integral: {
    color: fontColorBlack,
    marginRight: px2dp(24),
    fontSize: px2dp(26)
  },
  integralPrice: {
    color: fontColorCoffee
  },
  headTitleContainer: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  headTitleText: {
    color: '#000',
    fontSize: 18,
    fontWeight: isAndroid ? '400' : 'bold'
  },
  headTitleImage: {
    marginLeft: px2dp(10),
    width: px2dp(20),
    height: px2dp(20)
  },
});
